package spring.transactional;

import aop.Events;
import aop.event.ReturnEvent;
import aop.impl.EventsImpl;
import aop.listener.AbstractMethodListener;
import aop.listener.MethodListener;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.transaction.PlatformTransactionManager;

import java.util.Map;

public class TransactionConfigurationSelector implements ImportSelector, InitializingBean, ApplicationContextAware {
    private static final String PACKAGES_VALUE_NAME = "value";

    public void setTransactionManager(PlatformTransactionManager transactionManager) {
        System.out.println("TransactionManagementConfigurationSelector.setTransactionManager()");
    }
    //    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("TransactionManagementConfigurationSelector2.afterPropertiesSet()");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("TransactionManagementConfigurationSelector2.setApplicationContext()");
    }
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(EnableNextTransaction.class.getName());
       String packages = (String) annotationAttributes.get(PACKAGES_VALUE_NAME);
        if (packages == null || packages.isEmpty()) {
            String appClassName = importingClassMetadata.getClassName();
            packages = appClassName.substring(0, appClassName.lastIndexOf("."));
        }
        TxMethodListener.packages = packages;
        //        Class<?> annType = GenericTypeResolver.resolveTypeArgument(getClass(), EnableNextTransaction.class);
//
//        AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);

        Events events = EventsImpl.getInstance();

        events.addEventListener("org.springframework.transaction.annotation.TransactionManagementConfigurationSelector.selectImports(org.springframework.context.annotation.AdviceMode)", new AbstractMethodListener() {
            public void afterReturn(ReturnEvent event) {
                event.$return(new String[]{"org.springframework.context.annotation.AutoProxyRegistrar"});
            }
        });

        MethodListener listener = new AbstractMethodListener() {};
        TxMethodListener.add(packages, listener);

        return new String[]{TxMethodListener.class.getName()};
    }
}
